package io.github.cchenxi.crpc.core.consumer.http;

import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;

import io.github.cchenxi.crpc.core.api.RpcRequest;
import io.github.cchenxi.crpc.core.api.RpcResponse;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * OkHttpInvoker
 * Date: 2024-03-23
 *
 * @author chenxi
 */
public class OkHttpInvoker implements HttpInvoker {
    private static final MediaType JSON_TYPE = MediaType.get("application/json; charset=utf-8");

    OkHttpClient client;

    public OkHttpInvoker() {
        client = new OkHttpClient.Builder()
                .connectionPool(new ConnectionPool(16, 60, TimeUnit.SECONDS))
                .readTimeout(Duration.ofSeconds(100L))
                .writeTimeout(Duration.ofSeconds(100L))
                .connectTimeout(Duration.ofSeconds(100L))
                .build();
    }

    @Override
    public RpcResponse<?> post(RpcRequest rpcRequest, String url) {
        String requestJson = JSON.toJSONString(rpcRequest);
        System.out.println("req = " + requestJson);
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(requestJson, JSON_TYPE))
                .build();
        try {
            String responseJson = client.newCall(request).execute().body().string();
            System.out.println("resp = " + responseJson);
            return JSON.parseObject(responseJson, RpcResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
